package com.boarsoft.boar.message.server.config;

import java.io.File;
import java.io.FileFilter;
import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import com.boarsoft.boar.message.entity.RecipientQueueEntity;
import com.boarsoft.boar.message.entity.TargetQueueEntity;
import com.boarsoft.boar.message.service.MsgServerService;
import com.boarsoft.common.util.FileUtil;
//import com.boarsoft.common.util.FileUtil;
import com.boarsoft.message.MessageConfig;
import com.boarsoft.message.broker.MessageBroker;

/**
 * 此类在message-server启动时，从message-web获取队列信息，实现队列的动态加载和列新
 * 
 * @author Mac_J
 *
 */
public class MsgServerConfiger {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	/** 此broker指向本地的messageContext，不走RPC */
	@Autowired
	@Lazy
	protected MessageBroker broker;
	@Autowired
	@Lazy
	protected MsgServerService msgServerSvc;

	protected String regex = "^((tq|rq)\\_)(.*)(\\.xml)$";

	@PostConstruct
	public void init() {
		try {
			this.load();
		} catch(Exception e) {
			log.warn("Can not load queue config from remote");
			log.debug("Error on load queue config from remote", e);
		}
	}

	public void load() {
		// 先测试message-web是否可用
		if (msgServerSvc.test()) {
			// 如果可用，则删除本地的队列配置文件
			String dir = new StringBuilder(MessageConfig.APP_ROOT)//
					.append(MessageConfig.CONF_DIR).toString();
			File df = new File(dir);
			log.warn("Delete contents of directory {}", df.getAbsolutePath());
			FileUtil.deleteContents(df, new FileFilter() {
				@Override
				public boolean accept(File f) {
					return f.getName().matches(regex);
				}
			});
		}
		// 必须先初始化收件人队列
		List<RecipientQueueEntity> rqLt = msgServerSvc.getRecipientsQueues();
		for (RecipientQueueEntity rq : rqLt) {
			try {
				broker.addRecipientQueue(rq.getCode(), rq.getXml());
			} catch (Throwable e) {
				log.error("Error on add recipient queue {}", rq.getId(), e);
			}
		}
		// 再初始化主队列
		List<TargetQueueEntity> tqLt = msgServerSvc.getTargetQueues();
		for (TargetQueueEntity tq : tqLt) {
			try {
				broker.addTargetQueue(tq.getCode(), tq.getXml());
			} catch (Throwable e) {
				log.error("Error on add target queue {}", tq.getId(), e);
			}
		}
	}

	public String getRegex() {
		return regex;
	}

	public void setRegex(String regex) {
		this.regex = regex;
	}
}